package bdz.projects.atwww.electrolux.model.core
{
	import flash.events.EventDispatcher;
	import flash.utils.Dictionary;

	public class ELOption extends EventDispatcher {
		
		private var _alias:String;
		private var _subs:Dictionary;
		private var _currentSelected:String;
		private var _optIndex:Number = 0;
		private var _included:Boolean;
		public var customSelected:Object;
		public function ELOption(xm:XML)	{	
			super();
			_subs = new Dictionary();
			initialize(xm);
		}
		private function initialize(xm:XML):void{
			_alias = xm.@name;
			_included = xm.@included != "0";
			for each(var xo:XML in xm.option){
				addOption(xo.@key, xo);
			}
			
		}		
		private function setSelectedValue(key:String):void{
			_currentSelected = key;			
		}
		private function addOption(key:String, xo:XML):void{
			
			_subs[key] = {value:xo.@value, index:_optIndex, key:xo.@key, time:Number(xo.@time), enabled:xo.@enabled == "1"};
			try{
				_subs[key].selected = xo.@default == "1";
				if(_subs[key].selected){
					setSelectedValue(key);
				}
			}catch(e:Error){
				_subs[key].selected = false;
			}
			_optIndex++;
			
		}
		public function get selections():Array{
			var retarr:Array = new Array();
			var counter:Number = 0;
			for (var key:String in _subs){
				
				retarr[counter] = _subs[key];
				counter++;
			}
			retarr.sortOn("index", Array.NUMERIC);
			
			return retarr;
		}
		public function get alias():String{
			return _alias;
		}
		public function set selected(str:*):void{
			_currentSelected = str.toString();
		}
		public function get selected():*{
			return customSelected || _subs[_currentSelected];
		}
		public function get included():Boolean{
			return _included;
		}
		public function get serialize():XML{
			var xm:XML = new XML("<options/>");
			xm.@name = _alias;
			xm.@included = _included ? "1" : "0";
			var opts:XMLList = new XMLList();
			var counter:Number = 0;
			var sels:Array = selections;
			for each(var xkey:Object in sels){
				var opt:XML = new XML("<option/>");
				opt.@key = xkey.key;
				opt.@value = xkey.value;
				opt.@time = xkey.time;
				opt.@enabled = xkey.enabled ? "1" : "0";
				if(xkey.key == _currentSelected){
					opt.@default = "1";
				}
				opts[counter] = opt;
				counter++;
			}
			xm.option = opts;
			return xm;
		}
		
		
	}
}